<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<el-input placeholder="请输入标题" v-model="article.title">
				<template slot="prepend">标题</template>
			</el-input>
		</div>
		<div class="editor-container">
			<span class="editor-text">内容</span>
			<UE :defaultMsg=defaultMsg :config=config ref="ue"></UE>
			<el-row class="editor-row">
				<span class="editor-text">文章所属</span>
				<el-col :span="8">
					<el-select v-model="article.course" placeholder="请选择所属课程" @input="selectCourse">
						<el-option
								v-for="item in courseList"
								:key="item.courseId"
								:label="item.courseName"
								:value="item.courseId">
						</el-option>
					</el-select>
				</el-col>
				<el-col :span="16">
					<el-col :span="8">
						<el-select v-model="article.SN1Index" :disabled="!isSelectCourse" placeholder="请选择所属章" @input="selectSN1">
							<el-option
									v-for="(item,index) in data1"
									:key="index"
									:label="item.name"
									:value="index">
							</el-option>
						</el-select>
					</el-col>
					<el-col :span="8">
						<el-select v-model="article.SN2Index" :disabled="!isSelectSN1" placeholder="请选择所属节" @input="selectSN2">
							<el-option
									v-for="(item,index) in data2"
									:key="index"
									:label="item.name"
									:value="index">
							</el-option>
						</el-select>
					</el-col>
					<el-col :span="8">
						<el-select v-model="article.SN3Id" :disabled="!isSelectSN2" placeholder="请选择所属知识点">
							<el-option
									v-for="item in data3"
									:key="item.nodeId"
									:label="item.name"
									:value="item.nodeId">
							</el-option>
						</el-select>
					</el-col>
				</el-col>
			</el-row>
			<el-row class="editor-row">
				<span class="editor-text">文章标签<font>(多个标签之间用“/”分隔，最多不超过10个标签)</font></span>
				<el-input placeholder="请输入文章标签" v-model="article.tag">
				</el-input>
			</el-row>
			<el-row class="editor-row">
				<span class="editor-text">文章摘要</span>
				<el-input
						type="textarea"
						:autosize="{ minRows: 3, maxRows: 5}"
						placeholder="请输入文章摘要"
						v-model="article.remark">
				</el-input>
			</el-row>
			<el-row class="editor-row" style="text-align: right">
				<el-button type="primary" @click="getContent">发布文章</el-button>
				<el-button type="danger" @click="clearContent">清空内容</el-button>
			</el-row>
		</div>
	</el-card>
</template>

<script>
  import UE from '../ue.vue';
  import {getRelevancyList,getSectionStructure,saveArticleData} from '../../api/api';

  export default {
    components: {UE},
    data() {
      return {
        article:{
          title: '',
          content: '',
          course: '',
          SN1Index: '',
          SN2Index: '',
          SN3Id: '',
          tag: '',
          remark: ''
        },

		userId: '',
		userName: '',
		userDuty: '',

        courseList: [],

        selectedOptions:'',

        course:'',

        /*datass:{
          "atype": 0,
          "authorId": "string",
          "authorUserId": "string",
          "content": "string",
          "contentMD5": "string",
          "courseName": "string",
          "createDate": "2018-05-06T17:06:39.039Z",
          "href": "string",
          "id": "string",
          "knowledgePointId": "string",
          "knowledgePointName": "string",
          "orderNo": "string",
          "origin": "string",
          "recommendedId": "string",
          "remark": "string",
          "sectionName": "string",
          "status": 0,
          "tag": "string",
          "title": "string",
          "titleMD5": "string",
          "updateDate": "2018-05-06T17:06:39.039Z",
          "visitorsIds": [
            "string"
          ],
          "visitorsNum": 0
        },*/


        defaultMsg: '',

        textarea2: '',

        config: {
          initialFrameWidth: null,
          initialFrameHeight: 550,
          autoClearinitialContent:true,
          serverUrl:'http://192.168.31.154:8080/ueditor/ueditorUpload',
          zIndex:222,
          enableAutoSave:false,
          autoFloatEnabled:true,
          autoHeightEnabled:false,
		  toolbars: [
            [
              'undo', //撤销
              'redo', //重做
              '|',
              'forecolor', //字体颜色
              'backcolor', //背景色
              '|',
              'bold', //加粗
              'italic', //斜体
              'underline', //下划线
              'strikethrough', //删除线
              'fontborder', //字符边框
              '|',
              'horizontal', //分隔线
              'spechars', //特殊字符
              'blockquote', //引用
              'subscript', //下标
              'superscript', //上标
              '|',
              'paragraph', //段落格式
              'fontfamily', //字体
              'fontsize', //字号
              '|',
              'justifyleft', //居左对齐
              'justifyright', //居右对齐
              'justifycenter', //居中对齐
              'justifyjustify', //两端对齐
            ],
            [
              'insertorderedlist', //有序列表
              'insertunorderedlist', //无序列表
              'indent', //首行缩进
              '|',
              'rowspacingtop', //段前距
              'rowspacingbottom', //段后距
              'lineheight', //行间距
              '|',
              'touppercase', //字母大写
              'tolowercase', //字母小写
              '|',
              'link', //超链接
              'unlink', //取消链接
              'anchor', //锚点
              '|',
              'time', //时间
              'date', //日期
              'emotion', //表情
			  'simpleupload',
              'insertimage', //多图上传
              '|',
              'searchreplace', //查询替换
              'preview', //预览
              'selectall', //全选
              'cleardoc', //清空文档
              'help', //帮助
              '|',
              'source', //源代码
              'insertcode', //代码语言
            ],
            [
              'inserttable', //插入表格
              '|',
              'insertparagraphbeforetable', //"表格前插入行"
              'insertrow', //前插入行
              'insertcol', //前插入列
              'mergeright', //右合并单元格
              'mergedown', //下合并单元格
              'splittorows', //拆分成行
              'splittocols', //拆分成列
              'splittocells', //完全拆分单元格
              'inserttitle', //插入标题
              'mergecells', //合并多个单元格
              '|',
              'deleterow', //删除行
              'deletecol', //删除列
              'deletetable', //删除表格
              '|',
              'imagenone', //默认
              'imageleft', //左浮动
              'imageright', //右浮动
              'imagecenter', //居中
              '|',
              'cleardoc', //清空文档
            ],
          ]
        },



        select:'',
        input5:'',
        currentDate: new Date(),
        options: [],
        value: '',

        isSelectCourse: false,
        isSelectSN1: false,
        isSelectSN2: false,
        data1: [],
        data2: [],
        data3: [],

      };
    },
    methods: {
      clearContent() {
        let article = {
          title: '',
          content: '',
          course: '',
          SN1Index: '',
          SN2Index: '',
          SN3Id: '',
          tag: '',
          remark: ''
        };
        this.isSelectSN1 = false;
        this.isSelectSN2 = false;
        this.$refs.ue.clearContent('cleardoc');
      },
      getContent() {
		let jsonStr = {
          atype: 2,
          authorId: "",
		  teacherName: "",
          title: "",
          content: "",
          courseName: "",
          sectionName: "",
          knowledgePointId: "",
          knowledgePointName: "",
          tag: "",
          remark: "",
          origin: "校园云学习平台",
          visitorsIds: [],
          visitorsNum: 0
        };
        jsonStr.title = this.article.title;
		jsonStr.teacherName = this.userName +' '+this.userDuty;
		jsonStr.authorId = this.userId;
		jsonStr.content = this.$refs.ue.getUEContent();
        jsonStr.courseName = this.courseList.find(item => item.courseId === this.article.course)['courseName'];
        jsonStr.sectionName = this.data1[this.article.SN1Index].name+'/'+this.data1[this.article.SN1Index].childs[this.article.SN2Index].name;
        jsonStr.knowledgePointId = this.article.SN3Id;
        jsonStr.knowledgePointName =  this.data1[this.article.SN1Index]
		  .childs[this.article.SN2Index]
		  .childs.find(item => item.nodeId === this.article.SN3Id)['name'];
        jsonStr.tag = this.article.tag;
        jsonStr.remark = this.article.remark;
		console.log(jsonStr);
        saveArticleData(jsonStr).then((res) => {
          console.log(res);
        });
      },

      handleChange(value) {
        console.log(value);
      },

      selectCourse: function (val) {
        console.log(val);
        this.getSectionData(this.userId, val);
      },

      selectSN1: function () {
        console.log(this.data1);
        console.log(this.data1[this.article.SN1Index]);
        if(this.data1[this.article.SN1Index].childs.length>0) {
          console.log(1);
          this.article.SN2Index = 0;
          this.isSelectSN1 = true;
          this.data2 = this.data1[this.article.SN1Index].childs;
          this.selectSN2();
        }else{
          console.log(1);
          this.isSelectSN1 = false;
          this.isSelectSN2 = false;
          this.article.SN2Index = '此章节-章下无章节-节';
          this.article.SN3Id = '此章节-章下无知识点';
        }
      },

      selectSN2: function () {
        console.log(this.data1[this.article.SN1Index].childs[this.article.SN2Index]);
        if(this.data1[this.article.SN1Index].childs[this.article.SN2Index].childs.length > 0){
          this.data3 = this.data1[this.article.SN1Index].childs[this.article.SN2Index].childs;
          this.article.SN3Id = this.data3[0].nodeId;
          this.isSelectSN2 = true;
        }else{
          this.isSelectSN2 = false;
          this.article.SN3Id = '此章节-节下无知识点';
        }
      },

      getSectionData(val1, val2){
        console.log(val1+'\n'+val2);
        let para = {
          courseId: val2,
          teacherId: val1,
        };
        getSectionStructure(para).then((res) => {
          console.log(res.data.data[0].childs);
          if(res.data.data.length > 0){
            this.data1 = res.data.data[0].childs;
            this.isSelectCourse = true;
          }else {
            this.article.SN1Index = '此课程下无章节-章';
            this.article.SN2Index = '此课程下无章节-节';
            this.article.SN3Id = '此课程下无知识点';
          }
        });
      },

      getCourseData(val1,val2,val3) {
        let para = {
          count: 1000000,
          pageNo: this.page,
          sortDirection: 'asc',
          sortField: ["name"],
          departmentId: '',
          specialtyId: '',
          classId: '',
          courseId: '',
          year: val2,
          teacherId: val1,
          semester: val3,
        };
        getRelevancyList(para).then((res) => {
          console.log(res.data.data.content);
          let dataArr =  res.data.data.content;
          if(dataArr.length > 0){
            for(let i = 0; i < dataArr.length; i++){
              if(!this.courseList.find(item => item.courseId === dataArr[i]['courseId'])){
                this.courseList.push(dataArr[i]);
              }
            }
            console.log(this.courseList);
          }
        });
      },
      /*getUEContentTxt() {
        let content = this.$refs.ue.getUEContentTxt(); // 调用子组件方法
        this.$notify({
          title: '获取成功，可在控制台查看！',
          message: content,
          type: 'success'
        });
        console.log(content)
      }*/
    },

    mounted() {
      let newDate = new Date();
      let year = newDate.getFullYear();
      let val1 = year-1;
      let val2 = year+1;
      let schoolYear;
      let semester;
      let month = newDate.getMonth()+1;

      if(month >= 9){
        schoolYear = year+'-'+val2;
        semester = 1
      }else{
        schoolYear = val1+'-'+year;
        semester = 2
      }

      let user = sessionStorage.getItem('user');
      user = JSON.parse(user);

      this.userId = user.id;
      this.userName = user.name;
      this.userDuty = user.duty;
      this.getCourseData(user.id,schoolYear,semester);
    }
  }
</script>